// 用户相关自定义hook 

import { useState, useCallback } from 'react';
import {
  getCurrentUser as apiGetCurrentUser,
  getUserById as apiGetUserById,
  updateUserProfile as apiUpdateUserProfile,
  reviewAdminApplication as apiReviewAdminApplication,
} from '../api';
import {
  User,
  PublicUser,
  UpdateUserProfileRequest,
  ReviewAdminApplicationRequest,
} from '../types';
import { handleApiError, userStorage } from '../utils/api';

export const useUser = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 获取当前用户信息
  const getCurrentUser = useCallback(async () => {
    setLoading(true);
    setError(null);
    
    try {
      const response = await apiGetCurrentUser();
      if (response.code === 200) {
        userStorage.set(response.data);
        return response.data;
      } else {
        throw new Error(response.message);
      }
    } catch (err) {
      const errorMessage = handleApiError(err);
      setError(errorMessage);
      throw new Error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  // 查看指定用户信息
  const getUserById = useCallback(async (userId: number) => {
    setLoading(true);
    setError(null);
    
    try {
      const response = await apiGetUserById(userId);
      if (response.code === 200) {
        return response.data;
      } else {
        throw new Error(response.message);
      }
    } catch (err) {
      const errorMessage = handleApiError(err);
      setError(errorMessage);
      throw new Error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  // 更新个人信息
  const updateUserProfile = useCallback(async (data: UpdateUserProfileRequest) => {
    setLoading(true);
    setError(null);
    
    try {
      const response = await apiUpdateUserProfile(data);
      if (response.code === 200) {
        userStorage.set(response.data);
        return response.data;
      } else {
        throw new Error(response.message);
      }
    } catch (err) {
      const errorMessage = handleApiError(err);
      setError(errorMessage);
      throw new Error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  // 审核管理员申请
  const reviewAdminApplication = useCallback(async (userId: number, data: ReviewAdminApplicationRequest) => {
    setLoading(true);
    setError(null);
    
    try {
      const response = await apiReviewAdminApplication(userId, data);
      if (response.code === 200) {
        return response.data;
      } else {
        throw new Error(response.message);
      }
    } catch (err) {
      const errorMessage = handleApiError(err);
      setError(errorMessage);
      throw new Error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    loading,
    error,
    getCurrentUser,
    getUserById,
    updateUserProfile,
    reviewAdminApplication,
  };
}; 